import datetime
import json
from apps.pay.order.dao import OrderDao
from apps.merchant.sku.dao import SkuDao
from apps.merchant.item.dao import ItemDao



def checkOrders():
    # 取消30分钟之前待支付订单
    _orders = OrderDao().findAllMainOrder().filter(orderStatus='WAIT_PAY', createTime__lt=datetime.datetime.now()-datetime.timedelta(minutes=30))
    if _orders.exists():
        # 取消之后，释放库存
        for order in _orders:
            if order.content:
                content = json.loads(order.content)
                if not content.get('orderItemList'):
                    continue
                for item in content.get('orderItemList'):
                    if item.get('sku'):
                        SkuDao().addStock(item.get('sku'), item.get('payCount'))
    
        _orders.update(orderStatus='CANCEL')